package com.newvpn.fastbest.zenith.activity;


import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.shadowsocks.preference.DataStore;
import com.newvpn.fastbest.zenith.R;
import com.newvpn.fastbest.zenith.presenter.VPNPresenter;
import com.newvpn.fastbest.zenith.presenter.VPNReulst;
import com.newvpn.fastbest.zenith.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class AppsListActivity extends BaseActivity {


    private RecyclerView recyclerView;
    private AppsAdapter appsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v_activity_apps);
        initViews();
        loadDatas();
        //DataStore.INSTANCE.setBypass(true);
    }

    private void loadDatas() {
        showLoading();
        new GetAppListTask().execute();
    }

    private void initViews() {
        findViewById(R.id.ivBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        findViewById(R.id.ivRefresh).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                loadDatas();
//            }
//        });
        recyclerView = findViewById(R.id.recyclerView);
        appsAdapter = new AppsAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(AppsListActivity.this,LinearLayoutManager.VERTICAL,false));
        recyclerView.setAdapter(appsAdapter);
    }

    private class GetAppListTask extends AsyncTask<Void, Void, AllAppInfo> {
        @Override
        protected AllAppInfo doInBackground(Void... voids) {
            return getAppList();
        }

        @Override
        protected void onPostExecute(AllAppInfo appInfos) {
            appsAdapter.setAppList(appInfos.appInfoList,appInfos.infos);
            appsAdapter.notifyDataSetChanged();
            endLoading();
        }
    }


    private AllAppInfo getAppList() {
        AllAppInfo allAppInfo = new AllAppInfo();
        allAppInfo.infos = DataStore.INSTANCE.getIndividual();
        List<AppInfo> apps = new ArrayList<>();
        try {
            PackageManager pm = getPackageManager();
            for (ApplicationInfo appInfo : pm.getInstalledApplications(PackageManager.GET_META_DATA)) {
                AppInfo appInfo1 = new AppInfo();
                appInfo1.iconl = pm.getApplicationInfo(appInfo.packageName, 0).loadIcon(pm);
                appInfo1.label = pm.getApplicationLabel(appInfo).toString();
                appInfo1.packname = appInfo.packageName;
                apps.add(appInfo1);
            }
            Collections.sort(apps, new Comparator<AppInfo>() {
                @Override
                public int compare(AppInfo app1, AppInfo app2) {
                    boolean app1ContainsStr =  allAppInfo.infos.contains(app1.packname+"\n");
                    boolean app2ContainsStr =  allAppInfo.infos.contains(app2.packname+"\n");
                    // 如果两个应用的 label 都包含 str，按字母顺序排序
                    if (app1ContainsStr && app2ContainsStr) {
                        return app1.label.compareToIgnoreCase(app2.label);
                    }
                    // 如果 app1 的 label 包含 str，它应该排在前面
                    if (app1ContainsStr) {
                        return -1;
                    }
                    // 如果 app2 的 label 包含 str，它应该排在前面
                    if (app2ContainsStr) {
                        return 1;
                    }
                    // 如果都不包含 str，按字母顺序排序
                    return app1.label.compareToIgnoreCase(app2.label);
                }
            });
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        allAppInfo.appInfoList = apps;

        //DataStore.INSTANCE.setDirty(true);
        return allAppInfo;
    }


    private class AppInfo{
        String label;
        String packname;
        Drawable iconl;
    }

    private class AllAppInfo{
        List<AppInfo> appInfoList;
        String infos;
    }

    private class AppsAdapter extends RecyclerView.Adapter<AppsAdapter.AppViewHolder> {
        private List<AppInfo> allApps;
        private String allLimitApps = "";

        @Override
        public AppsAdapter.AppViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.v_item_app, parent, false);
            return new AppViewHolder(view);
        }

        @Override
        public void onBindViewHolder(AppsAdapter.AppViewHolder holder, int position) {
            AppInfo app = allApps.get(position);
            String appInfo = app.packname;
            holder.appName.setText(app.label);
            holder.appIcon.setImageDrawable(app.iconl);
            boolean isCheck = !allLimitApps.contains(appInfo+ "\n");
            holder.appStatus.setImageResource(isCheck ? R.drawable.v_turn_on : R.drawable.v_turn_off);

            holder.appStatus.setOnClickListener(v -> {
                if (isCheck) {
                    allLimitApps = allLimitApps + appInfo + "\n";
                    //AppsLimitUtils.saveConfig(appInfo);
                } else {
                    allLimitApps = allLimitApps.replace(appInfo + "\n", "");
                    //AppsLimitUtils.deleteConfig(AppsListActivity.this,appInfo);
                }
                DataStore.INSTANCE.setIndividual(allLimitApps);
                DataStore.INSTANCE.setDirty(true);
                //AppInfosUtils.save(getApplicationContext(),allApps);
                notifyDataSetChanged();
                if (VPNPresenter.INSTANCE.getVPNStatus() != VPNReulst.STATE_DISCONNECT){
                    ToastUtils.show(R.string.work_next_time);
                }

//                Profile profile = ProfileManager.INSTANCE.getProfile("1");
//                profile.setBypass(true);
//                profile.setIndividual();
//                profile.id = profileId
//                profile.deserialize()
//                ProfileManager.updateProfile(profile)
//                ProfilesFragment.instance?.profilesAdapter?.deepRefreshId(profileId)
//                if (profileId in Core.activeProfileIds && DataStore.directBootAware) DirectBoot.update()


            });
        }

        @Override
        public int getItemCount() {
            if (allApps == null){
                return 0;
            }
            return allApps.size();
        }

        public void setAppList(List<AppInfo> appInfos,String infos) {
            allApps = appInfos;
            allLimitApps = infos;
        }

        class AppViewHolder extends RecyclerView.ViewHolder {
            ImageView appIcon;
            TextView appName;
            ImageView appStatus;

            AppViewHolder(View itemView) {
                super(itemView);
                appIcon = itemView.findViewById(R.id.icon);
                appName = itemView.findViewById(R.id.name);
                appStatus = itemView.findViewById(R.id.status);
            }
        }
    }


}
